package com.umessage.hotel.rest;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

import javax.servlet.ServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.umessage.common.shiro.JwtFilter;
import com.umessage.common.shiro.JwtToken;
import com.umessage.common.util.JsonWebTokenUtil;
import com.umessage.hotel.domain.UserMenu;
import com.umessage.hotel.model.AccountModel;
import com.umessage.hotel.service.UserMemberService;
import com.umessage.hotel.util.ErrorCode;
import com.umessage.hotel.util.RestResult;
import com.umessage.hotel.util.RestResultGenerator;
import com.umessage.system.domain.Menu;
import com.umessage.system.domain.User;
import com.umessage.system.service.MenuService;
import com.umessage.system.service.UserService;

import io.jsonwebtoken.SignatureAlgorithm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Api("员工管理")
@RestController
@EnableAutoConfiguration
@RequestMapping("/rest/accounts")
public class AccountResource {

	private final long refreshPeriodTime = 36000L;

	private final long period = 36000L * 24 * 7;;

	@Autowired
	private MenuService menuService;
	@Autowired
	private UserService userService;
	@Autowired
	private UserMemberService userMemberService;

/*	@ApiOperation(value = "员工登录", notes = "酒店员工登录通过小程序登录")
	@ApiImplicitParams({ @ApiImplicitParam(name = "hotelId", value = "酒店ID", required = true, paramType = "query"),
			@ApiImplicitParam(name = "mobile", value = "酒店手机号", required = true, paramType = "query"),
			@ApiImplicitParam(name = "code", value = "临时登录凭证", required = true, paramType = "query"),
			@ApiImplicitParam(name = "vercode", value = "手机验证码", required = true, paramType = "query") })
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public RestResult<AccountModel> login(String hotelId, String mobile, String code, String vercode) {
		Subject user = SecurityUtils.getSubject();
		JwtToken jwtToken = new JwtToken(hotelId, mobile, code, vercode);
		try {
			user.login(jwtToken);
			if (user.isAuthenticated()) {
				String openid = (String) user.getPrincipal();
				// 获取用户信息
				User hotelUser = userService.findUserByMobile(hotelId, mobile);
				if (hotelUser == null) {
					return RestResultGenerator.genErrorResult("unexist user");
				}

				List<UserMenu> usermenuList = userMemberService.getUserMeList(hotelUser.getUserId().toString());

				List<String> menuPermsList = Arrays.asList("order_wait_confirm", "order_wait_confirm:confirm_button",
						"order_wait_confirm:cancel_button", "order_wait_pay", "order_confirmed",
						"oorder_confirmed:cancel_button", "order_cancelled", "order_all", "order_all:confirm_button",
						"order_all:cancel_button", "room_status", "room_status:book_button", "room_status:change_price");

				Map privilege = new TreeMap();

				for (UserMenu um : usermenuList) {
					if (um.getMenuId() != null && !"undefined".equals(um.getMenuId())) {
						Menu mu = menuService.selectByKey(Long.valueOf(um.getMenuId()));
						if (menuPermsList.contains(mu.getPerms())) {
							String perms = mu.getPerms();
							String[] permArr = perms.split(":");
							Map entry = null;
							if (privilege.containsKey(permArr[0])) {
								entry = (Map) privilege.get(permArr[0]);
							} else {
								entry = new TreeMap();
								privilege.put(permArr[0], entry);
							}
							if (permArr.length == 1) {
								entry.put("list", true);
							} else if (permArr.length == 2) {
								entry.put(permArr[1], true);
							}

						}
					}
				}

				AccountModel accountInfo = new AccountModel();
				accountInfo.setPrivilege(privilege);
				accountInfo.setAccountId(String.valueOf(hotelUser.getUserId()));
				accountInfo.setHotelId(hotelUser.getHotelId());
				accountInfo.setAccountName(hotelUser.getUsername());
				accountInfo.setSex(hotelUser.getSsex());
				accountInfo.setHeadImgUrl(hotelUser.getAvatar());
				accountInfo.setMobile(hotelUser.getMobile());

				String jwt = JsonWebTokenUtil.issueJWT(openid, accountInfo.getAccountId(), hotelId,
						JwtFilter.HOTEL_MINI_PROGRAM, period, "user", null, "3", SignatureAlgorithm.HS512);
				accountInfo.setSessionId(jwt);
				return RestResultGenerator.genSuccessResult(accountInfo);
			}
			return RestResultGenerator.genErrorResult("unauthorized");
		} catch (AuthenticationException e) {
			e.printStackTrace();
			return RestResultGenerator.genErrorResult(e.getMessage());
		}
	}
*/
	@ApiOperation(value = "员工退出", notes = "酒店员工退出小程序登录")
	@RequestMapping(value = "/logout", method = RequestMethod.POST)
	public RestResult logout() {
		try {
			Subject user = SecurityUtils.getSubject();
			user.logout();
			return RestResultGenerator.genSuccessResult();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return RestResultGenerator.genErrorResult(ErrorCode.SERVER_ERROR);
		}
	}

	private AccountModel getAccountInfo() {
		AccountModel account = new AccountModel();
		account.setSessionId(UUID.randomUUID().toString());
		account.setAccountId(UUID.randomUUID().toString());
		account.setHotelId(UUID.randomUUID().toString());
		account.setMobile("18700000000");
		account.setPhone("99999999");
		return account;
	}
	
	@ApiOperation(value = "员工权限", notes = "更新小程序酒店员工权限")
	@RequestMapping(value = "/privilege", method = RequestMethod.POST)
	public Map getPrivilege(ServletRequest request) {
		String userId = (String) request.getAttribute("subject");
		//String hotelId = (String) request.getAttribute("issuer");
		List<UserMenu> usermenuList = userMemberService.getUserMeList(userId);
		List<String> menuPermsList = Arrays.asList("order_wait_confirm", "order_wait_confirm:confirm_button",
				"order_wait_confirm:cancel_button", "order_wait_pay", "order_confirmed",
				"oorder_confirmed:cancel_button", "order_cancelled", "order_all", "order_all:confirm_button",
				"order_all:cancel_button", "room_status", "room_status:book_button", "room_status:change_price","memberinvoice:list");
		Map privilege = new TreeMap();
		for (UserMenu um : usermenuList) {
			if (um.getMenuId() != null && !"undefined".equals(um.getMenuId())) {
				Menu mu = menuService.selectByKey(Long.valueOf(um.getMenuId()));
				if (menuPermsList.contains(mu.getPerms())) {
					String perms = mu.getPerms();
					String[] permArr = perms.split(":");
					Map entry = null;
					if (privilege.containsKey(permArr[0])) {
						entry = (Map) privilege.get(permArr[0]);
					} else {
						entry = new TreeMap();
						privilege.put(permArr[0], entry);
					}
					if (permArr.length == 1) {
						entry.put("list", true);
					} else if (permArr.length == 2) {
						entry.put(permArr[1], true);
					}

				}
			}
		}
		return privilege;
		}

	
	@ApiOperation(value = "员工登录", notes = "酒店员工登录通过小程序登录")
	@ApiImplicitParams({@ApiImplicitParam(name = "mobile", value = "酒店手机号", required = true, paramType = "query"),
			@ApiImplicitParam(name = "code", value = "临时登录凭证", required = true, paramType = "query"),
			@ApiImplicitParam(name = "vercode", value = "手机验证码", required = true, paramType = "query") })
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public RestResult<AccountModel> login(String mobile, String code, String vercode) {
		User hotelUser = userService.findUserByMobileNum(mobile);
		if (hotelUser == null) {
			return RestResultGenerator.genErrorResult("unexist user");
		}
		Subject user = SecurityUtils.getSubject();
		String hotelId=hotelUser.getHotelId();
		JwtToken jwtToken = new JwtToken(hotelId,mobile, code, vercode);
		try {
			user.login(jwtToken);
			if (user.isAuthenticated()) {
				String openid = (String) user.getPrincipal();
				// 获取用户信息
				/*User hotelUser = userService.findUserByMobileNum(mobile);
				if (hotelUser == null) {
					return RestResultGenerator.genErrorResult("unexist user");
				}*/

				List<UserMenu> usermenuList = userMemberService.getUserMeList(hotelUser.getUserId().toString());

				List<String> menuPermsList = Arrays.asList("order_wait_confirm", "order_wait_confirm:confirm_button",
						"order_wait_confirm:cancel_button", "order_wait_pay", "order_confirmed",
						"oorder_confirmed:cancel_button", "order_cancelled", "order_all", "order_all:confirm_button",
						"order_all:cancel_button", "room_status", "room_status:book_button", "room_status:change_price","memberinvoice:list");

				Map privilege = new TreeMap();

				for (UserMenu um : usermenuList) {
					if (um.getMenuId() != null && !"undefined".equals(um.getMenuId())) {
						Menu mu = menuService.selectByKey(Long.valueOf(um.getMenuId()));
						if (menuPermsList.contains(mu.getPerms())) {
							String perms = mu.getPerms();
							String[] permArr = perms.split(":");
							Map entry = null;
							if (privilege.containsKey(permArr[0])) {
								entry = (Map) privilege.get(permArr[0]);
							} else {
								entry = new TreeMap();
								privilege.put(permArr[0], entry);
							}
							if (permArr.length == 1) {
								entry.put("list", true);
							} else if (permArr.length == 2) {
								entry.put(permArr[1], true);
							}

						}
					}
				}

				AccountModel accountInfo = new AccountModel();
				accountInfo.setPrivilege(privilege);
				accountInfo.setAccountId(String.valueOf(hotelUser.getUserId()));
				accountInfo.setHotelId(hotelUser.getHotelId());
				accountInfo.setAccountName(hotelUser.getUsername());
				accountInfo.setSex(hotelUser.getSsex());
				accountInfo.setHeadImgUrl(hotelUser.getAvatar());
				accountInfo.setMobile(hotelUser.getMobile());

				String jwt = JsonWebTokenUtil.issueJWT(openid, accountInfo.getAccountId(),hotelId,
						JwtFilter.HOTEL_MINI_PROGRAM, period, "user", null, "3", SignatureAlgorithm.HS512);
				accountInfo.setSessionId(jwt);
				return RestResultGenerator.genSuccessResult(accountInfo);
			}
			return RestResultGenerator.genErrorResult("unauthorized");
		} catch (AuthenticationException e) {
			e.printStackTrace();
			return RestResultGenerator.genErrorResult(e.getMessage());
		}
	}
}
